package org.bigtree.example.common.frame.handles;

import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.bigtree.example.common.exception.BaseException;
import org.bigtree.example.common.webapi.ResponseResult;
import org.bigtree.example.constans.ResponseCode;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author bigTree
 * @since 2025/4/25
 */
@Slf4j
@RestControllerAdvice
public class GeneralExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<?> paramValidateException(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        e.getAllErrors().forEach((error) -> {
            if (error instanceof FieldError fieldError) {
                sb.append(fieldError.getField()).append(":").append(error.getDefaultMessage());
            }
        });
        log.error(sb.toString());
        return ResponseResult.fail(ResponseCode.PARAMETER_INVALID);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseResult<?> businessException(HttpMessageNotReadableException e) {
        log.error(Throwables.getRootCause(e).getMessage());
        return ResponseResult.fail(ResponseCode.ENUM_INVALID);
    }

    @ExceptionHandler(BaseException.class)
    public ResponseResult<?> businessException(BaseException e) {
        log.error(Throwables.getRootCause(e).getMessage());
        return ResponseResult.fail(e.getRespCode());
    }

    @ExceptionHandler(Exception.class)
    public ResponseResult<?> otherException(Exception e) {
        e.printStackTrace();
        log.error(Throwables.getRootCause(e).getMessage());
        return ResponseResult.fail(ResponseCode.FAIL);
    }
}
